"""
风险分析模块（核心）
从stock_analyzer.py迁移，保持API不变
"""

import numpy as np


class RiskAnalyzer:
    """风险分析类（保持向后兼容）"""
    
    @staticmethod
    def calculate_volatility(df, period=20):
        """计算波动率"""
        if len(df) < period:
            return None
        
        returns = df['收盘'].pct_change()
        volatility = returns.rolling(window=period).std() * np.sqrt(252) * 100
        return volatility.iloc[-1]
    
    @staticmethod
    def calculate_max_drawdown(df):
        """计算最大回撤"""
        if len(df) < 2:
            return None
        
        cummax = df['收盘'].cummax()
        drawdown = (df['收盘'] - cummax) / cummax * 100
        return drawdown.min()
    
    @staticmethod
    def calculate_sharpe_ratio(df, period=60):
        """计算夏普比率"""
        if len(df) < period:
            return None
        
        returns = df['收盘'].pct_change().tail(period)
        sharpe = returns.mean() / returns.std() * np.sqrt(252)
        return sharpe
    
    @staticmethod
    def analyze_risk(df):
        """综合风险分析"""
        risk_info = {}
        
        # 波动率
        volatility = RiskAnalyzer.calculate_volatility(df)
        if volatility:
            risk_info['波动率'] = f"{volatility:.2f}%"
            if volatility < 20:
                risk_info['波动率评价'] = "低波动"
            elif volatility < 35:
                risk_info['波动率评价'] = "中等波动"
            else:
                risk_info['波动率评价'] = "高波动"
        
        # 最大回撤
        max_dd = RiskAnalyzer.calculate_max_drawdown(df)
        if max_dd:
            risk_info['最大回撤'] = f"{max_dd:.2f}%"
            if max_dd > -10:
                risk_info['回撤评价'] = "回撤较小"
            elif max_dd > -20:
                risk_info['回撤评价'] = "回撤中等"
            else:
                risk_info['回撤评价'] = "回撤较大，风险高"
        
        # 夏普比率
        sharpe = RiskAnalyzer.calculate_sharpe_ratio(df)
        if sharpe:
            risk_info['夏普比率'] = f"{sharpe:.2f}"
            if sharpe > 1:
                risk_info['夏普评价'] = "收益风险比良好"
            elif sharpe > 0:
                risk_info['夏普评价'] = "收益风险比一般"
            else:
                risk_info['夏普评价'] = "收益风险比较差"
        
        return risk_info

